package com.sxm.yiwei.activitis;

import android.Manifest;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Parcelable;
import android.provider.MediaStore;
import android.support.annotation.RequiresApi;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AlertDialog;
import android.support.v7.view.ContextThemeWrapper;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sxm.yiwei.MainActivity;
import com.sxm.yiwei.R;
import com.sxm.yiwei.tools.BaseIntents;
import com.sxm.yiwei.tools.CropPictures;
import com.sxm.yiwei.utils.InternetAddressUtis;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class PickUpActivity extends BaseActivity implements View.OnClickListener{

    private ImageView pickupback;
    private ImageView pickupimg1,pickupimg2,pickupimg3,pickupimg4;
    private Button pickupsend;
    /*用来标识请求照相功能的activity*/
    private static final int CAMERA_WITH_DATA = 3023;
    private static final int PHOTO_TEXT = 3022;
    private static final int ADDRESS = 1001;
    /*用来标识请求gallery的activity*/
    private static final int PHOTO_PICKED_WITH_DATA = 3021;
    private ArrayList<String> mList = new ArrayList<String>();
    private List<String> imglist = new ArrayList();
    private List<Object> imgId = new ArrayList<>();
    /*拍照的照片存储位置*/
    private static final File PHOTO_DIR = new File(Environment.getExternalStorageDirectory() + "/DCIM/Camera");
    private File mCurrentPhotoFile;
    private Bitmap photo;
    // 按钮标志
    private int currentIndex;
    private String path1;
    private SharedPreferences sharedPreferences;
    private String appId;
    private String userId;
    private String token;
    private String id;
    private String from;
    private TextView title;
    private AlertDialog dialog,dialog1;
    private TextView picktype;
    private BaseIntents baseIntents;
    private ImageView backmain;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pick_up);
        sharedPreferences = getSharedPreferences("userlogin", Context.MODE_PRIVATE);
        appId = sharedPreferences.getString("appid", "0");
        userId = sharedPreferences.getString("userId", "1");
        token = sharedPreferences.getString("token", "2");
        initPickUpView();
        baseIntents = new BaseIntents();
        Intent intent = getIntent();
        id = intent.getStringExtra("id");
        from = intent.getStringExtra("from");
        if (from.equals("1")){
            title.setText("取货");
            pickupsend.setText("出发");
            picktype.setText("请上传取货凭证");
        }else {
            picktype.setText("请上传送达凭证");
            title.setText("送达");
            pickupsend.setText("送达");
        }
    }

    private void initPickUpView() {
        backmain = (ImageView) findViewById(R.id.pickup_backmain);
        pickupback = (ImageView) findViewById(R.id.pickupbook_back);
        pickupimg1 = (ImageView) findViewById(R.id.pickupbook_img1);
        pickupimg2 = (ImageView) findViewById(R.id.pickupbook_img2);
        pickupimg3 = (ImageView) findViewById(R.id.pickupbook_img3);
        pickupimg4 = (ImageView) findViewById(R.id.pickupbook_img4);
        pickupsend = (Button) findViewById(R.id.pickupbook_send);
        picktype = (TextView) findViewById(R.id.pick_type);

        title = (TextView) findViewById(R.id.pickup_title);

        pickupback.setOnClickListener(this);
        pickupimg1.setOnClickListener(this);
        pickupimg2.setOnClickListener(this);
        pickupimg3.setOnClickListener(this);
        pickupimg4.setOnClickListener(this);
        pickupsend.setOnClickListener(this);
        backmain.setOnClickListener(this);

    }
    private void doPickPhotoAction() {
        final Context context = this;
        AlertDialog.Builder b1 = new AlertDialog.Builder(context);
        View view = LayoutInflater.from(context).inflate(R.layout.picture_dialog, null);
        b1.setView(view);

        TextView camere = (TextView) view.findViewById(R.id.picdia_camere);
        TextView pic = (TextView) view.findViewById(R.id.picdia_pic);
        TextView cancel1 = (TextView) view.findViewById(R.id.picdia_cancel);

        final AlertDialog dialog1 = b1.create();
        Window window = dialog1.getWindow();
        camere.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String status= Environment.getExternalStorageState();
                if(status.equals(Environment.MEDIA_MOUNTED)){//判断是否有SD卡
                    // index=0;
                    baseIntents.doTakePhoto();// 用户点击了从照相机获取
                    dialog1.dismiss();
                }
                else{
                    Toast.makeText(context, "没有SD卡", Toast.LENGTH_SHORT).show();
                }
            }
        });
        pic.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                baseIntents.doPickPhotoFromGallery();// 从相册中去获取
                dialog1.dismiss();
            }
        });
        cancel1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog1.dismiss();
            }
        });
        dialog1.show();
        window.setGravity(Gravity.BOTTOM);
    }

    // 因为调用了Camera和Gally所以要判断他们各自的返回情况,他们启动时是这样的startActivityForResult
    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != RESULT_OK)
            return;
        switch (requestCode) {
            case PHOTO_PICKED_WITH_DATA: {// 调用Gallery返回的
                photo = data.getParcelableExtra("data");
                String s = CropPictures.saveBitmapFile(photo, baseIntents.getPhotoFileName());
                imglist.add(s);
                if (currentIndex==1){
                    pickupimg1.setImageBitmap(photo);
                }else if (currentIndex==2){
                    pickupimg2.setImageBitmap(photo);
                }else if (currentIndex==3){
                    pickupimg3.setImageBitmap(photo);
                }else if (currentIndex==4){
                    pickupimg4.setImageBitmap(photo);
                }
                break;
            }
            case CAMERA_WITH_DATA: {// 照相机程序返回的,再次调用图片剪辑程序去修剪图片
                baseIntents.doCropPhoto(baseIntents.mCurrentPhotoFile);

                break;
            }
            case PHOTO_TEXT:
                Uri data1 = data.getData();
                if (!TextUtils.isEmpty(data1.getAuthority())){
                    ContentResolver resolver = getContentResolver();
                    try {
                        photo = MediaStore.Images.Media.getBitmap(resolver, data1);
                        String[] proj = {MediaStore.Images.Media.DATA};
                        Cursor cursor = managedQuery(data1, proj, null, null, null);
                        if (cursor==null){
                            Toast.makeText(this, "没有找到图片", Toast.LENGTH_SHORT).show();
                        }else {
                            cursor.moveToFirst();
                            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                            //图片路径
                            path1 = cursor.getString(column_index);

                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }else {
                    path1 = data1.getPath();
                }
                File file = new File(path1);
                baseIntents.doCropPhoto(file);
                break;

        }
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.pickup_backmain:
                startActivity(new Intent(PickUpActivity.this, MainActivity.class));
                AppManager.getAppManager().finishAllActivity();
                break;
            case R.id.pickupbook_back:
                finish();
                break;
            case R.id.pickupbook_img1:
                currentIndex = 1;
                doPickPhotoAction();
                break;
            case R.id.pickupbook_img2:
                currentIndex = 2;
                doPickPhotoAction();
                break;
            case R.id.pickupbook_img3:
                currentIndex = 3;
                doPickPhotoAction();
                break;
            case R.id.pickupbook_img4:
                currentIndex = 4;
                doPickPhotoAction();
                break;
            case R.id.pickupbook_send:
                int size = imglist.size();

                if (from.equals("1")){
                    if (size>=1){
                      /*  AlertDialog.Builder builder = new AlertDialog.Builder(PickUpActivity.this,R.style.NoBackGroundDialog);
                        View view = LayoutInflater.from(this).inflate(R.layout.progress_dialog, null);
                        ProgressBar diapro = (ProgressBar) view.findViewById(R.id.pro_dia);
                        builder.setView(view);
                        dialog1 = builder.create();
                        dialog1.show();*/
                        sendBookImg(InternetAddressUtis.GETBOOK);
                    }else {
                        Toast.makeText(this, "为了交易安全,请至少上传一张照片", Toast.LENGTH_SHORT).show();
                    }
                }else {
                    if (size>=1){
                        /*AlertDialog.Builder builder = new AlertDialog.Builder(PickUpActivity.this,R.style.NoBackGroundDialog);
                        View view = LayoutInflater.from(this).inflate(R.layout.progress_dialog, null);
                        ProgressBar diapro = (ProgressBar) view.findViewById(R.id.pro_dia);
                        builder.setView(view);
                        dialog1 = builder.create();
                        dialog1.show();*/
                        sendBookImg(InternetAddressUtis.DISPATCHBOOK);
                    }else {
                        Toast.makeText(this, "为了交易安全,请至少上传一张照片", Toast.LENGTH_SHORT).show();
                    }
                }
                break;
        }
    }
        // 取货 / 送达方法
    private void sendBookImg(String url) {
        RequestParams params = new RequestParams(InternetAddressUtis.Url+url);
        params.addHeader("Content-Type","application/json");
        params.addHeader("token",token);
        params.addHeader("appId",appId);
        params.addHeader("userId",userId);
        JSONObject j = new JSONObject();
        params.addBodyParameter("orderId",id);
        for (int i = 0; i < imglist.size(); i++) {
            if (from.equals("1")){
                params.addBodyParameter("order_pickup",new File(imglist.get(i)));
            }else {
                params.addBodyParameter("delivery",new File(imglist.get(i)));
            }

        }

        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
               // dialog1.dismiss();
                AlertDialog.Builder builder = new AlertDialog.Builder(PickUpActivity.this,R.style.NoBackGroundDialog);
                View view = LayoutInflater.from(PickUpActivity.this).inflate(R.layout.pick_dalog, null);
                builder.setView(view);
                TextView cont = (TextView) view.findViewById(R.id.content_t);
                Button surebt = (Button) view.findViewById(R.id.pick_surebt);
                if (from.equals("1")){
                    cont.setText("取货成功,像飞一样的出发吧");
                }else {
                    cont.setText("确认送达成功");
                }

                final AlertDialog dialog2 = builder.create();
                surebt.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                        finish();
                        dialog2.dismiss();
                    }
                });
                dialog2.show();

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }
}
